package appx.craft.droid.ui;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import appx.craft.droid.R;
import appx.craft.droid.bean.FeedBean;
import appx.craft.droid.bean.JSONParams;
import appx.craft.droid.stricky.StickyListHeadersListView;
import appx.craft.droid.stricky.StickyListHeadersListView.OnHeaderClickListener;
import appx.craft.droid.uc.FeedAdapter;
import appx.craft.droid.uc.IFeedUploadListener;
import appx.craft.droid.uc.IHeaderListener;
import appx.craft.droid.uc.TabMenuClickListener;
import appx.craft.droid.utils.Constance;
import appx.craft.droid.utils.JSONParser;
import appx.craft.droid.utils.Log;
import appx.craft.droid.utils.UtilityHelper;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class FeedListingActivity extends FragmentActivity implements
		OnScrollListener, AdapterView.OnItemClickListener,
		OnHeaderClickListener, TabMenuClickListener, onFeedCommentClickListner,IFeedUploadListener,IHeaderListener{

	private final String TAG = FeedListingActivity.class.getCanonicalName();

	public static final String TAG_STATUS_MESSAGE = "statusmsg";
	public static final String TAG_STATUS = "status";
	public static final String TAG_PHOTOS_ARRAY = "Photos";

	public static final String TAG_PROFILE_ID = "ProfileID";
	public static final String TAG_FEED_ID = "FeedID";
	public static final String TAG_FILE_PATH = "FilePath";
	public static final String TAG_CREATED = "Created";
	public static final String TAG_Name = "Name";
	public static final String TAG_CAPTION = "Caption";

	private int startIndex = 0;

	private static final String KEY_LIST_POSITION = "KEY_LIST_POSITION";

	private int firstVisible;

	public FeedAdapter mFeedAdapter;
	private StickyListHeadersListView stickyList;
	private ProgressBar toggleIndeterminate_top_bar;

	boolean loadingMore;

	private Handler mPullHeader = new Handler();

	// image cache idea
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	public DisplayImageOptions mOptions;
	private boolean instanceStateSaved;

	private Button btn_refresh_pull;

	/**
	 * REQUEST CODE OF IMAGE GALLRY
	 */
	public static final int RESULT_LOAD_IMAGE = 1;

	public static final int RESULT_SHARE_IMAGE = 2;
	
	private TextView textView_timestemp;
	
	@Override
	protected void onCreate(Bundle saveInstance) {
		super.onCreate(saveInstance);
		Log.d(TAG, "[onCreate ]");
		setContentView(R.layout.activity_feed_listing);
		
		mOptions = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.ic_launcher)
				.resetViewBeforeLoading().cacheInMemory().cacheOnDisc().build();

		textView_timestemp = (TextView)findViewById(R.id.textView_timestemp);
		textView_timestemp.setVisibility(View.GONE);
		
		stickyList = (StickyListHeadersListView) findViewById(R.id.stickyListHeadersListView);
		stickyList.setSmoothScrollbarEnabled(true);
		stickyList.setAreHeadersSticky(false);
		stickyList.setDivider(new ColorDrawable(0x0000ffff));
		stickyList.setDividerHeight(1);
		stickyList.setOnItemClickListener(this);
		stickyList.setOnHeaderClickListener(this);

		if (saveInstance != null) {
			firstVisible = saveInstance.getInt(KEY_LIST_POSITION);
		}

		toggleIndeterminate_top_bar = (ProgressBar) findViewById(R.id.toggleIndeterminate_top_bar);

		mFeedAdapter = new FeedAdapter(this, imageLoader, mOptions);
		stickyList.setAdapter(mFeedAdapter);
		stickyList.setSelection(firstVisible);

		startIndex = 0;
		if (UtilityHelper.isOnline(FeedListingActivity.this)) {
			new getFeedList().execute(new Integer[] { startIndex });
		} else {
			Toast.makeText(getApplicationContext(),
					"Please check internet connection !!!", Toast.LENGTH_LONG)
					.show();
		}

		btn_refresh_pull = (Button) findViewById(R.id.btn_refresh_pull);
		btn_refresh_pull.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/** If network is available then **/
				if (UtilityHelper.isOnline(FeedListingActivity.this)) {
					
					if(FeedAdapter.mFeedMessageList != null && FeedAdapter.mFeedMessageList.size() > 0){
						String mLatestFeedID = null;
						for (int i = 0; i < FeedAdapter.mFeedMessageList.size(); i++) 
						{
							String strFeedType = FeedAdapter.mFeedMessageList.get(i).getTypeID();
							if(strFeedType.equalsIgnoreCase(Constance.VIEW_DOWNLOAD)){
								
								mLatestFeedID = FeedAdapter.mFeedMessageList.get(i).getFeedID();
								
								break;
							}
							
						}
						
						if(mLatestFeedID != null){
							
							new getLatestFeeds().execute(new String[] {mLatestFeedID});
						}
							
					}
					
					/*
					 * if(startIndex == 0 && isloadFirstTime){
					 * mFeedAdapter.clearFeedList(); new
					 * getFeedList().execute(new Integer[] {startIndex});
					 * isloadFirstTime = false; }else{
					 * 
					 * startIndex = startIndex + Constance.LIMIT_PAGE; new
					 * getFeedList().execute(new Integer[] {startIndex}); }
					 */

				} else {
					Toast.makeText(getApplicationContext(),"Please check internet connection !!!",Toast.LENGTH_LONG).show();
				}

			}
		});

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		instanceStateSaved = true;
		outState.putInt(KEY_LIST_POSITION, firstVisible);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// mFeedAdapter.clearFeedList();
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG, "[onStart ]");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG, "[onStop]");
	}

	@Override
	protected void onDestroy() {
		Log.d(TAG, "[onDestroy]");
		startIndex = 0;
		/** we must clear cache memory for reuse  **/
		imageLoader.clearMemoryCache();
		/** we must clear cache memory for reuse  **/
		imageLoader.clearDiscCache();
		if (!instanceStateSaved) {
			Log.d(TAG, "[ stop imageLoader ]");
			/** if any download thread is still running we must stop on destroy **/
			imageLoader.stop();
		}
		super.onDestroy();

	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "[onPause]");
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		int lastInScreen = firstVisibleItem + visibleItemCount;
		/** On scroll down we add old feeds  **/
		if ((lastInScreen == totalItemCount) && !(loadingMore)) {
			if (UtilityHelper.isOnline(FeedListingActivity.this)) {
				loadingMore = true;
				startIndex = startIndex + Constance.LIMIT_PAGE;
				new getFeedList().execute(new Integer[] { startIndex });

			} else {
				Toast.makeText(getApplicationContext(),
						"Please check internet connection !!!",
						Toast.LENGTH_LONG).show();
			}

		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onHeaderClick(StickyListHeadersListView l, View header,
			int itemPosition, long headerId, boolean currentlySticky) {
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	}

	@Override
	public void onMenuItemClick(int buttonID) {
		// TODO Auto-generated method stub
		if (buttonID == R.id.btn_top_feeds) {
		} else if (buttonID == R.id.btn_camera) {

			UtilityHelper.openCustomIntent(FeedListingActivity.this,
					RESULT_LOAD_IMAGE, "image/*");

		} else if (buttonID == R.id.btn_serach) {
		}
	}
	
	/**
	 * 
	 * Fetch Latest feeds from server during scroll down from top to bottom
	 *
	 */
	class getFeedList extends AsyncTask<Integer, Void, Integer> {

		private ArrayList<FeedBean> mTempFeedList;
		private int tempIndex;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			mPullHeader.postDelayed(new Runnable() {

				@Override
				public void run() {
					toggleIndeterminate_top_bar.setVisibility(View.VISIBLE);
					btn_refresh_pull.setVisibility(View.INVISIBLE);
				}
			}, 1000);

			mTempFeedList = new ArrayList<FeedBean>();
		}

		@Override
		protected Integer doInBackground(Integer... params) {

			int result = 0;
			try {

				ArrayList<JSONParams> mArrayParams;
				JSONParams mObj$Params;
				mArrayParams = new ArrayList<JSONParams>();

				mObj$Params = new JSONParams();
				mObj$Params.setStrKey(Constance.PARAM_OFFSET);
				mObj$Params.setStrvalue(String.valueOf(params[0]));
				tempIndex = params[0];
				mArrayParams.add(mObj$Params);

				mObj$Params = new JSONParams();
				mObj$Params.setStrKey(Constance.PARAM_LIMIT);
				mObj$Params.setStrvalue(String.valueOf(Constance.LIMIT_PAGE)); // default
																				// 10
																				// limit
				mArrayParams.add(mObj$Params);

				JSONArray mPhotosJsonArray = null;
				// Creating JSON Parser instance
				JSONParser jParser = new JSONParser();

				// getting JSON string from URL
				JSONObject mJson = jParser.getJSONFromUrl(
						Constance.GET_FEED_URL, mArrayParams);
				
				Log.d(TAG, "[ mJSON ]" + mJson.toString());
				
				String mStatus = mJson.getString(TAG_STATUS);
				String mMessage = mJson.getString(TAG_STATUS_MESSAGE);

				Log.d(TAG, "[ STATUS ]" + mStatus);
				Log.d(TAG, "[ MESSAGE ]" + mMessage);

				if (mMessage.equalsIgnoreCase("Ok")) {
					result = 200;
					// Getting Array of TAG_PHOTOS_ARRAY
					mPhotosJsonArray = mJson.getJSONArray(TAG_PHOTOS_ARRAY);

					FeedBean mBeanofFeeds;

					if (mPhotosJsonArray.length() > 0) {

						for (int i = 0; i < mPhotosJsonArray.length(); i++) {

							mBeanofFeeds = new FeedBean();
							JSONObject mObjectMessage = mPhotosJsonArray
									.getJSONObject(i);

							String mProfileName = new String(
									mObjectMessage.getString(TAG_Name));
							String mCaption = new String(
									mObjectMessage.getString(TAG_CAPTION));
							String mFeedID = new String(
									mObjectMessage.getString(TAG_FEED_ID));
							String mFilePath = new String(
									mObjectMessage.getString(TAG_FILE_PATH));
							String mFileCreated = new String(
									mObjectMessage.getString(TAG_CREATED));

							// Download View Type
							mBeanofFeeds.setTypeID(Constance.VIEW_DOWNLOAD);
							mBeanofFeeds.setProfileID("");
							mBeanofFeeds.setFeedID(mFeedID);
							mBeanofFeeds.setName(mProfileName);
							mBeanofFeeds.setDisplayName("");
							mBeanofFeeds.setCaptionText(mCaption);
							mBeanofFeeds.setLikeCounter("0");
							mBeanofFeeds.setFilePath(mFilePath);
							mBeanofFeeds.setCreatedDateTime(mFileCreated);

							mTempFeedList.add(mBeanofFeeds);

						}
					} else {
						result = 401;
					}

				} else {
					result = -1;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

			return result;
		}

		@Override
		protected void onPostExecute(Integer result) {

			// hide toggle progress bar
			mPullHeader.postDelayed(new Runnable() {

				@Override
				public void run() {
					toggleIndeterminate_top_bar.setVisibility(View.INVISIBLE);
					btn_refresh_pull.setVisibility(View.VISIBLE);
				}
			}, 1000);

			if (result > -1) {

				if (result == 200) {

					for (FeedBean mMessage : mTempFeedList) {
						mFeedAdapter.addNewFeedItem(mMessage);
					}
					
					loadingMore = false;
					stickyList.setOnScrollListener(FeedListingActivity.this);
					
					
				} else if (result == 401) {

					loadingMore = false;
					startIndex = tempIndex != 0 ? (tempIndex - 10) : 0;
				}
			}
		}

	}
	
	/**
	 * 
	 * Fetch Latest feed ID from server during press on [refresh ] button
	 *
	 */
	class getLatestFeeds extends AsyncTask<String, Void, Integer> {
		
		ArrayList<FeedBean> mTempFeedList;
		String mStatusMessage="";
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			mPullHeader.postDelayed(new Runnable() {

				@Override
				public void run() {
					toggleIndeterminate_top_bar.setVisibility(View.VISIBLE);
					btn_refresh_pull.setVisibility(View.INVISIBLE);
				}
			}, 1000);
			
			mTempFeedList = new ArrayList<FeedBean>();
		}
		
		@Override
		protected Integer doInBackground(String... params) {
			int result = 0;
			try {
				
				
				ArrayList<JSONParams> mArrayParams;
				JSONParams mObj$Params;
				mArrayParams = new ArrayList<JSONParams>();

				mObj$Params = new JSONParams();
				mObj$Params.setStrKey(Constance.PARAM_LATEST_ID);
				mObj$Params.setStrvalue(String.valueOf(params[0]));
				
				Log.d(TAG, "[ PARAM_LATEST_ID ]" + String.valueOf(params[0]));
				
				mArrayParams.add(mObj$Params);

				
				JSONArray mPhotosJsonArray = null;
				
				// Creating JSON Parser instance
				JSONParser jParser = new JSONParser();

				// getting JSON string from URL
				JSONObject mJson = jParser.getJSONFromUrl(Constance.GET_FEED_BY_LATEST, mArrayParams);
				
				
				Log.d(TAG, "[ mJSON ]" + mJson.toString());
				
				String mStatus = mJson.getString(TAG_STATUS);
				String mMessage = mJson.getString(TAG_STATUS_MESSAGE);

				mStatusMessage = mStatus;
				Log.d(TAG, "[ STATUS ]" + mStatus);
				Log.d(TAG, "[ MESSAGE ]" + mMessage);

				if (mMessage.equalsIgnoreCase("Ok")) {
					
					result = 200;
					// Getting Array of TAG_PHOTOS_ARRAY
					mPhotosJsonArray = mJson.getJSONArray(TAG_PHOTOS_ARRAY);
					
					
					FeedBean mBeanofFeeds;

					if (mPhotosJsonArray.length() > 0) {

						for (int i = 0; i < mPhotosJsonArray.length(); i++) {

							mBeanofFeeds = new FeedBean();
							JSONObject mObjectMessage = mPhotosJsonArray
									.getJSONObject(i);

							String mProfileName = new String(
									mObjectMessage.getString(TAG_Name));
							String mCaption = new String(
									mObjectMessage.getString(TAG_CAPTION));
							String mFeedID = new String(
									mObjectMessage.getString(TAG_FEED_ID));
							String mFilePath = new String(
									mObjectMessage.getString(TAG_FILE_PATH));
							String mFileCreated = new String(
									mObjectMessage.getString(TAG_CREATED));

							// Download View Type
							mBeanofFeeds.setTypeID(Constance.VIEW_DOWNLOAD);
							mBeanofFeeds.setProfileID("");
							mBeanofFeeds.setFeedID(mFeedID);
							mBeanofFeeds.setName(mProfileName);
							mBeanofFeeds.setDisplayName("");
							mBeanofFeeds.setCaptionText(mCaption);
							mBeanofFeeds.setLikeCounter("0");
							mBeanofFeeds.setFilePath(mFilePath);
							mBeanofFeeds.setCreatedDateTime(mFileCreated);
							mBeanofFeeds.setFlagIsNew(false);
							mBeanofFeeds.setFlagIsUpLoadedCancel(false);
							
						
							mTempFeedList.add(mBeanofFeeds);

						}
						
					} else {
						
						result = 401;
					}

				} else {
					
					result = 501;
				}

				
			}catch (Exception e) {
				e.printStackTrace();
				Log.d(TAG, e.toString());
			}
			return result;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			// hide toggle progress bar
			if(result == 200){
				
				if(mTempFeedList != null){
					
					for (FeedBean mMessage : mTempFeedList) {
						mFeedAdapter.updateFeed(mMessage);
					}
				}

			}else {
				
				Toast.makeText(FeedListingActivity.this, mStatusMessage,Toast.LENGTH_SHORT).show();
			}
			
			mPullHeader.postDelayed(new Runnable() {

				@Override
				public void run() {
					toggleIndeterminate_top_bar.setVisibility(View.INVISIBLE);
					btn_refresh_pull.setVisibility(View.VISIBLE);
				}
			}, 1000);
			
		}
	}

	/**
	 * on Feed when any once click on comment
	 */
	@Override
	public void onStreamCommentClick(int position) {
		startActivity(new Intent(FeedListingActivity.this,
				StreamCommentActivity.class));
	}
	
	/**
	 * go from  Feed list to liker list 
	 */
	@Override
	public void onStreamLikerListClick(int position) {
		startActivity(new Intent(FeedListingActivity.this, LikersActivity.class));
	}
	
	/**
	 * press on photo for sliding screen 
	 */
	@Override
	public void onStreamPhotoSlidingClick(int position) {
		Intent mIntent = new Intent(FeedListingActivity.this,
				SlideShowActivity.class);
		mIntent.putExtra(Constance.INTENT_PHOTO_POSITION,
				String.valueOf(position));
		startActivity(mIntent);
	}

	/**
	 * Once press on profile icon in feed listing screen for move on profile screen 
	 */
	@Override
	public void onProfileIconClick(int position) {
		startActivity(new Intent(FeedListingActivity.this,
				ProfileActivity.class));
	}

	/**
	 * we here when we come back to the gallery or camera screen
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Log.d(TAG, "[ onActivityResult ] ");
		/** IF IMAGE RESULT **/
		if (requestCode == RESULT_LOAD_IMAGE) {

			if (resultCode == RESULT_OK) {

				Log.d(TAG, "[ resultCode == RESULT_OK ] ");

				String picturePath = null;

				if (data == null) {

					Log.d(TAG, "[ data == null ] ");
					File dir = new File(Constance.IMAGE_DIR);
					File output = new File(dir, "camerascript.png");
					if (output.exists()) {
						picturePath = output.getAbsolutePath();
					}

				} else {

					Log.d(TAG, "[ data != null ] ");
					if (data.getData() != null) {
						Uri selectedImage = data.getData();
						Log.d(TAG, "[ URI ] " + selectedImage.getPath());
						picturePath = UtilityHelper.getRealPathFromURI(
								FeedListingActivity.this, selectedImage);

					} else {

						File dir = new File(Constance.IMAGE_DIR);
						File output = new File(dir, "camerascript.png");
						if (output.exists()) {
							picturePath = output.getAbsolutePath();
						}
					}

				}

				if (picturePath.endsWith(".PNG")
						|| picturePath.endsWith(".JPEG")
						|| picturePath.endsWith(".jpeg")
						|| picturePath.endsWith(".jpg")
						|| picturePath.endsWith(".JPG")
						|| picturePath.endsWith(".png")) {

					Log.d(TAG, "[ picturePath] " + picturePath);
					Intent mShareIntent = new Intent(FeedListingActivity.this,
							PreviewImagesActivity.class);
					mShareIntent.putExtra(Constance.INTENT_KEY_IMAGE_PATH,
							picturePath);
					startActivityForResult(mShareIntent,RESULT_SHARE_IMAGE);
					
					
				}

			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(), "Result canceled !!!",
						1000 * 1).show();
			}
		}

		if (requestCode == RESULT_SHARE_IMAGE) {

			if (resultCode == RESULT_OK) {
				Log.d(TAG, "[ resultCode == RESULT_OK ] ");
				String imagePath = data.getExtras().getString(
						Constance.INTENT_KEY_IMAGE_PATH);
				String mCaption = data.getExtras().getString(
						Constance.INTENT_CAPTION);

				if (mFeedAdapter != null) {

					FeedBean mTempBean = new FeedBean();

					mTempBean.setTypeID(Constance.VIEW_UPLOAD);
					mTempBean.setFeedID("");
					mTempBean.setProfileID("");
					
					mTempBean.setName("testaccount@gmail.com");
					mTempBean.setCaptionText(mCaption);
					mTempBean.setFilePath(imagePath);
					mTempBean.setLikeCounter("0");
					
					Calendar c = Calendar.getInstance();
					SimpleDateFormat df = new SimpleDateFormat(
							"dd MMM yyyy hh:mm a");
					String formattedDate = df.format(c.getTime());
					mTempBean.setCreatedDateTime(formattedDate);
					
					mTempBean.setFlagIsNew(true);
					mTempBean.setFlagIsUpLoadedCancel(false);
					
					mFeedAdapter.addFirstFeed(mTempBean);
					
					runOnUiThread(new Runnable() {
						
						@SuppressLint("NewApi")
						@Override
						public void run() {
							stickyList.setSelection(0);
						}
					});
					
				}
			}

		}

	}
	
	@Override
	public void onUploadListener(boolean falg) {
	/*	if(falg){
			
			if (UtilityHelper.isOnline(FeedListingActivity.this)) {
				
				if(FeedAdapter.mFeedMessageList != null && FeedAdapter.mFeedMessageList.size() > 0){
					String mLatestFeedID = FeedAdapter.mFeedMessageList.get(0).getFeedID();
					
					if(mLatestFeedID != null){
						
						new getLatestFeeds().execute(new String[] {mLatestFeedID});
					}
						
				}
				
				
				 * if(startIndex == 0 && isloadFirstTime){
				 * mFeedAdapter.clearFeedList(); new
				 * getFeedList().execute(new Integer[] {startIndex});
				 * isloadFirstTime = false; }else{
				 * 
				 * startIndex = startIndex + Constance.LIMIT_PAGE; new
				 * getFeedList().execute(new Integer[] {startIndex}); }
				 

			} else {
				Toast.makeText(getApplicationContext(),"Please check internet connection !!!",Toast.LENGTH_LONG).show();
			}
		}*/
	}
	
	/**
	 * This will help to update date in sticky header on top right corner 
	 * @param timestemp
	 */
	public void resetFeedHeader(final String timestemp){
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
			  	textView_timestemp.setText(timestemp);
			}
		});
	}

	/**
	 *  This will help to update header view 
	 */
	@Override
	public void resetHeaderView(int position) {
		
		if(!textView_timestemp.isShown()){
			textView_timestemp.setVisibility(View.VISIBLE);	
		}
		final String latestDate = UtilityHelper.extractDateFromTimeStemp(FeedAdapter.mFeedMessageList.get(position).getCreatedDateTime());
		resetFeedHeader(latestDate);
	}
}
